package com.zy.business.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.business.domain.TbPunchCard;
import com.zy.business.domain.TbReissueCard;
import com.zy.business.mapper.PunchCardMapper;
import com.zy.business.mapper.ReissueCardMapper;
import com.zy.business.service.ReissueCardService;
import com.zy.common.core.domain.AjaxResult;
import com.zy.common.core.domain.entity.SysDept;
import com.zy.common.core.domain.entity.SysUser;
import com.zy.common.utils.SecurityUtils;
import com.zy.common.utils.WebUtil;
import com.zy.system.mapper.SysDeptMapper;
import com.zy.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @description: 补卡 服务层实现
 * @author: whf
 * @create: 2022-07-30 16:46
 **/
@Service
public class ReissueCardServiceImpl extends ServiceImpl<ReissueCardMapper, TbReissueCard> implements ReissueCardService {

    @Autowired
    private PunchCardMapper punchCardMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Value("${APPID}")
    private String APPID;

    @Value("${APPSECRET}")
    private String APPSECRET;

    @Value("${REISSUE_RESULT}")
    private String resultTemplateId;

    @Value("${REISSUE_APPLY}")
    private String applyTemplateId;

    @Override
    @Transactional
    public AjaxResult saveReissueCard(TbReissueCard reissueCard) {
        TbPunchCard punchCard = punchCardMapper.selectById(reissueCard.getPunchCardId());
        reissueCard.setUserId(punchCard.getUserId());
        reissueCard.setCreateTime(new Date());
        baseMapper.insert(reissueCard);
        this.sendMessage(reissueCard,1);
        return AjaxResult.success();
    }

    @Override
    public List<TbReissueCard> getReissueCardList(Integer type, Integer status) {
        Long userId = SecurityUtils.getUserId();
        List<TbReissueCard> reissueCardList = baseMapper.getReissueCardList(type,status,userId);
        return reissueCardList;
    }

    @Override
    public AjaxResult auditReissue(TbReissueCard oldReissueCard) {
        TbReissueCard reissueCard = baseMapper.selectById(oldReissueCard.getId());
        reissueCard.setStatus(oldReissueCard.getStatus());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (oldReissueCard.getStatus()==1){
            TbPunchCard punchCard = punchCardMapper.selectById(reissueCard.getPunchCardId());
            String dateTime = sdf.format(punchCard.getCreateTime());
            if (punchCard.getState()==1){
                dateTime += " 08:30:00";
            }else if (punchCard.getState()==2){
                dateTime += " 11:30:00";
            }else if (punchCard.getState()==3){
                dateTime += " 13:30:00";
            }else if (punchCard.getState()==4){
                dateTime += " 18:00:00";
            }
            try {
                punchCard.setPunchCardTime(sdf1.parse(dateTime));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            punchCard.setStatus(4);
            punchCard.setUpdateTime(new Date());
            punchCardMapper.updateById(punchCard);
        }
        reissueCard.setAuditReason(oldReissueCard.getAuditReason());
        reissueCard.setAuditTime(new Date());
        baseMapper.updateById(reissueCard);
        this.sendMessage(reissueCard,2);
        return AjaxResult.success();
    }

    public void sendMessage(TbReissueCard reissueCard, Integer type){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SysUser applyUser = userMapper.selectUserById(reissueCard.getUserId());
        TbPunchCard punchCard = punchCardMapper.selectById(reissueCard.getPunchCardId());
        SysDept dept = deptMapper.selectDeptById(applyUser.getDeptId());
        SysUser auditUser = userMapper.selectUserById(reissueCard.getAuditUserId());
        String accessUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET;
        JSONObject result = WebUtil.doGet(accessUrl);
        String accessToken = null;
        if (null != result) {
            accessToken = result.getString("access_token");
        }
        String templtUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+accessToken;
        String toUser = "";
        String templateId = "";
        String remarkStr = "";
        String firstStr = "";
        String keyStr1 = "";
        String keyStr2 = "";
        String keyStr3 = "";
        String keyStr4 = "";
        String date = sdf.format(punchCard.getCreateTime());
        if (punchCard.getState()==1){
            date += " 08:30";
        }else if (punchCard.getState()==2){
            date += " 11:30";
        }else if (punchCard.getState()==3){
            date += " 13:30";
        }else if (punchCard.getState()==4){
            date += " 18:00";
        }
        //补卡提醒
        if (type==1){
            toUser = auditUser.getOpenId();
            templateId = applyTemplateId;
            firstStr = "您有一个新的补卡申请待审核！";
            keyStr1 = applyUser.getUserName();
            keyStr2 = dept.getDeptName();
            keyStr3 = date;
            keyStr4 = reissueCard.getApplyReason();
            remarkStr = "请尽快审核";
        }else{
            //补卡结果通知
            String resultStr = "";
            if (reissueCard.getStatus()==2){
                resultStr = "未通过";
            }else {
                resultStr = "已通过";
            }
            toUser = applyUser.getOpenId();
            templateId = resultTemplateId;
            firstStr = "您的补卡申请"+resultStr+"！";
            keyStr1 = dept.getDeptName();
            keyStr2 = date;
            keyStr3 = reissueCard.getApplyReason();
            remarkStr = reissueCard.getAuditReason();
        }
        String url = "http://kq.heshenghua.net/office/#/cardspDetail?openId="+toUser+"&reissueId="+reissueCard.getId();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("touser", toUser);   // openid
        jsonObject.put("template_id", templateId);
        jsonObject.put("url", url);

        JSONObject data = new JSONObject();
        JSONObject first = new JSONObject();
        first.put("value", firstStr);
        first.put("color", "#173177");

        JSONObject keyword1 = new JSONObject();
        keyword1.put("value", keyStr1);
        keyword1.put("color", "#173177");

        JSONObject keyword2 = new JSONObject();
        keyword2.put("value", keyStr2);
        keyword2.put("color", "#173177");

        JSONObject keyword3 = new JSONObject();
        keyword3.put("value", keyStr3);
        keyword3.put("color", "#173177");

        JSONObject keyword4 = new JSONObject();
        keyword4.put("value", keyStr4);
        keyword4.put("color", "#173177");

        JSONObject remark = new JSONObject();
        remark.put("value", remarkStr);
        remark.put("color", "#173177");

        data.put("first",first);
        data.put("keyword1",keyword1);
        data.put("keyword2",keyword2);
        data.put("keyword3",keyword3);
        if (type==1){
            data.put("keyword4",keyword4);
        }
        data.put("remark",remark);

        jsonObject.put("data", data);

        String string = null;
        try {
            string = WebUtil.sendPostJsonStr(templtUrl, jsonObject.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONObject result1 = JSONObject.parseObject(string);
        int errcode = result1.getIntValue("errcode");
        if(errcode == 0){
            // 发送成功
            System.out.println("发送成功");
        } else {
            // 发送失败
            System.out.println("发送失败");
        }
    }
}
